package com.xiaodong.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.javafx.geom.BaseBounds;
import com.xiaodong.reggie.currency.R;
import com.xiaodong.reggie.dto.DishDto;
import com.xiaodong.reggie.entity.*;
import com.xiaodong.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.BaseBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //查询分类数据
    @GetMapping("/page")
    @Cacheable(value = "dish_shou",key = "#page+'dish_'+#pageSize")
    public R<Page> page(int page, int pageSize, String name) {

        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> pageInfo1 = new Page();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();

        queryWrapper.orderByAsc(Dish::getSort);

        if (name != null) {
            queryWrapper.like(Dish::getName, name);
        }

        dishService.page(pageInfo, queryWrapper);

        //拷贝对象
        BeanUtils.copyProperties(pageInfo, pageInfo1, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            //拷贝对象
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);
            return dishDto;

        }).collect(Collectors.toList());

        pageInfo1.setRecords(list);

        return R.success(pageInfo1);
    }

    //新型菜品添加和菜品口味
    @PostMapping
    @CacheEvict(value = "dish_shou",allEntries = true)  //删除全部套餐数据
    public R<String> save(@RequestBody DishDto dishDto) {

        dishService.saveByDto(dishDto);

        //清理redis里面的数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("添加了一道新菜");

    }

    //数据回显
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto dishAndFlavor = dishService.getDishAndFlavor(id);

        if (dishAndFlavor != null) {
            return R.success(dishAndFlavor);
        }

        return R.error("没有查询到对应菜品信息");
    }

    //修改菜单类型或顺序
    @PutMapping
    @CacheEvict(value = "dish_shou",allEntries = true)  //删除全部套餐数据
    public R<String> update(@RequestBody DishDto dishDto) {

//        categoryService.updateById(category);
        dishService.updateDishAndFlavor(dishDto);

        //清理redis里面的数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //精确清理redis里面的数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改成功");

    }

    //停售
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish_shou",allEntries = true)  //删除全部套餐数据
    public R<String> status(@PathVariable int status, Long[] ids) {

        for (int i = 0; i < ids.length; i++) {
            Dish dish = new Dish();
            dish.setId(ids[i]);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("该菜品已经修改成功");

    }

    //删除菜品
    @DeleteMapping
    @CacheEvict(value = "dish_shou",allEntries = true)  //删除全部套餐数据
    public R<String> delete(Long[] ids) {

//        log.info("id的值：={}", ids);

        List<Long> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(ids[i]);
        }

        dishService.removeByIds(list);

        return R.success("删除成功");

    }

//    //套餐餐品查询
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//
//        log.info("标号的值是=={}",dish.getCategoryId());
//
//        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
//        queryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return R.success(list);
//    }

    //套餐餐品查询
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        List<DishDto> list1 = null;

        //从key中获取缓存数据
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        list1 = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (list1 != null) {
            return R.success(list1);
        }

        //log.info("标号的值是=={}", dish.getCategoryId());

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);


        list1 = list.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishDto.getId());
            List<DishFlavor> one = dishFlavorService.list(queryWrapper1);

            dishDto.setFlavors(one);

            return dishDto;

        }).collect(Collectors.toList());

        //将从数据库查询到的数据存储到redis中、
        redisTemplate.opsForValue().set(key, list1, 60, TimeUnit.MINUTES);

        return R.success(list1);
    }
}
